<?php
namespace app\api\model;
use Think\Db;
use app\common\service\Message;
use think\facade\Hook;
use think\facade\Request;
use app\common\model\Orderagent as DealerOrderModel;
use app\common\exception\BaseException;
use app\common\model\Level as levelModel;
use app\common\model\AppPrepayId as AppPrepayIdModel;
use app\common\model\AgentCapital;
use app\common\model\Delivery;
use think\facade\Session;
/**
 * 订单模型
 * Class Order
 * @package app\common\model
 */
class Order extends BaseModel
{
    protected $name = 'order';
    protected $pk = 'order_id';
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'app_id',
        'update_time'
    ];


    /**
     * 设置错误信息
     */
    private function setError($error)
    {
        empty($this->error) && $this->error = $error;
    }
    /**
     * 是否存在错误
     */
    public function hasError()
    {
        return !empty($this->error);
    }

    /**
     * 订单模型初始化
     */
    public static function init()
    {
        parent::init();
        // 监听订单处理事件
        $static = new static;
        Hook::listen('order', $static);
    }
    /**
     * 订单详情信息
     * @return \think\model\relation\BelongsTo
     */
    public function orderMaster()
    {
        return $this->belongsTo('app\common\model\Order');
    }
    /**
     * 订单商品列表
     * @return \think\model\relation\HasMany
     */
    public function goods()
    {
        return $this->hasMany('OrderGoods');
    }
    /**
     * 关联物流列表
     * @return \think\model\relation\HasMany
     */
    public function OrderDelivery()
    {
        return $this->hasMany('OrderDelivery','order_no','order_no');
    }
    /**
     * 关联订单收货地址表
     * @return \think\model\relation\HasOne
     */
    public function address()
    {

        return $this->hasOne('OrderAddress');
    }
    /**
     * 关联用户表
     * @return \think\model\relation\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo('User');
    }

    /**
     * 关联物流公司表
     * @return \think\model\relation\BelongsTo
     */
    public function express()
    {
        return $this->hasMany('Express','express_id');
    }
    /**
     * 收货状态
     * @param $value
     * @return array
     */
    public function getOrderStatusAttr($value)
    {
        $status = [10 => '进行中', 20 => '取消', 30 => '已完成'];
        return ['text' => $status[$value], 'value' => $value];
    }
    /**
     * 生成订单号
     * @return string
     */
    protected function orderNo()
    {
        return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
    /**
     * 订单详情
     * @param $where
     * @return null|static
     * @throws \think\exception\DbException
     */
    public static function detail($where)
    {
        is_array($where) ? $filter = $where : $filter['order_id'] = (int)$where;
        return self::get($filter, ['goods.image', 'address','user','OrderDelivery']);
    }




    /**
     * 数据导出到excel(csv文件)
     * @param $fileName
     * @param array $tileArray
     * @param array $dataArray
     */
    function export_excel($fileName,$tileArray = [],$dataArray = [])
    {
        $file_name = "order-".(date('Ymdhis',time())).".csv";
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename='.$file_name );
        header('Cache-Control: max-age=0');
        $file = fopen('php://output',"a");
        $limit = 1000;
        $calc = 0;
        foreach ($tileArray as $v){
            $tit[] = iconv('UTF-8', 'GB2312//IGNORE',$v);
        }
        fputcsv($file,$tit);
        foreach ($dataArray as $v){
            $calc++;
            if($limit == $calc){
                ob_flush();
                flush();
                $calc = 0;
            }
            foreach($v as $t){
                $tarr[] = iconv('UTF-8', 'GB2312//IGNORE',$t);
            }
            fputcsv($file,$tarr);
            unset($tarr);
        }
        unset($list);
        fclose($file);
        exit();
    }

    function tab1ss($tab1s){
        $tab=explode('-',$tab1s);
        return "充值满".$tab[0].',减'.$tab[1];
    }

    function coupon($coupon){
        $str='<select name="prom[expression]">';
        foreach($coupon as $k=>$v){
            $str.='<option value="'.$v['coupon_id'].'">'.$v['name'].'</option>';
        }
        $str.='</select>';

        return $str;

    }

    function catname($cat_id){
        return db('category')->where(array('id'=>$cat_id))->value('name');
    }


    /**
     * 订单导出
     * @param $dataType
     * @param $query
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function exportList($dataType, $query)
    {
        // 获取订单列表
        $list = $this->getListAll($dataType, $query);
        // 表格标题
        $tileArray = ['订单号', '商品名称', '单价', '数量', '付款金额', '运费金额', '下单时间',
            '买家', '买家留言', '收货人姓名', '联系电话', '收货人地址', '物流公司', '物流单号',
            '付款状态', '付款时间', '发货状态', '发货时间', '收货状态', '收货时间', '订单状态',
            '微信支付交易号', '是否已评价'];
        // 表格内容
        $dataArray = [];
        foreach ($list as $order) {
            /* @var OrderAddress $address */
            $address = $order['address'];
            foreach ($order['goods'] as $Item) {
                $dataArray[] = [
                    '订单号' => $this->filterValue($order['order_no']),
                    '商品名称' => $Item['name'],
                    '单价' => $Item['goods_price'],
                    '数量' => $Item['total_num'],
                    '付款金额' => $this->filterValue($order['pay_price']),
                    '运费金额' => $this->filterValue($order['express_price']),
                    '下单时间' => $this->filterValue($order['create_time']),
                    '买家' => $this->filterValue($order['user']['nickName']),
                    '买家留言' => $this->filterValue($order['buyer_remark']),
                    '收货人姓名' => $this->filterValue($order['address']['name']),
                    '联系电话' => $this->filterValue($order['address']['phone']),
                    '收货人地址' => $this->filterValue($address ? $address->getFullAddress() : ''),
                    '物流公司' => $this->filterValue($order['express']['express_name']),
                    '物流单号' => $this->filterValue($order['express_no']),
                    '付款状态' => $this->filterValue($order['pay_status']['text']),
                    '付款时间' => $this->filterTime($order['pay_time']),
                    '发货状态' => $this->filterValue($order['delivery_status']['text']),
                    '发货时间' => $this->filterTime($order['delivery_time']),
                    '收货状态' => $this->filterValue($order['receipt_status']['text']),
                    '收货时间' => $this->filterTime($order['receipt_time']),
                    '订单状态' => $this->filterValue($order['order_status']['text']),
                    '微信支付交易号' => $this->filterValue($order['transaction_id']),
                    '是否已评价' => $this->filterValue($order['is_comment'] ? '是' : '否'),
                ];
            }
        }
        // 导出csv文件
        $filename = 'order-' . date('YmdHis');
        return export_excel($filename . '.csv', $tileArray, $dataArray);
    }
    /**
     * 批量发货模板
     */
    public function deliveryTpl()
    {
        // 导出csv文件
        $filename = 'delivery-' . date('YmdHis');
        return export_excel($filename . '.csv', ['订单号', '物流单号']);
    }
    /**
     * 表格值过滤
     * @param $value
     * @return string
     */
    private function filterValue($value)
    {
        return "\t" . $value . "\t";
    }
    /**
     * 日期值过滤
     * @param $value
     * @return string
     */
    private function filterTime($value)
    {
        if (!$value) return '';
        return $this->filterValue(date('Y-m-d H:i:s', $value));
    }

    /**
     * 确认发货
     */
    public function delivery($data, $sendMsg = true)
    {
        // 更新订单状态
        $status = $this->save([
            'delivery_status' => 20,
            'delivery_time' => time(),
        ]);
        $express=Express::detail($data['express_id']);

        $status=OrderDelivery::create([
            'express_id' => $data['express_id'],
            'order_no' => $this['order_no'],
            'company'=>$express['express_name'],
            'express_no' => $data['express_no'],
            'app_id'	=> self::$app_id,
            'type'       =>1
        ]);

        // 发送消息通知
        ($status && $sendMsg) && $this->deliveryMessage($this['order_id'],$express,$data['express_no']);

        return $status;
    }





    /**
     * 订单列表
     */
    public function getListsTwo($where = [],$field = '')
    {
        // 获取数据列表
        return DB::table('bfb_order')
            ->where($where)
            ->order(['create_time' => 'desc'])
            ->field($field)
            ->limit('0,10')
            ->select();
    }


    /**
     * 订单列表
     */
    public function getListsad($where = [],$field = '')
    {
        // 获取数据列表
        return DB::table('bfb_order')
            ->where($where)
            ->order(['create_time' => 'desc'])
            ->field($field)
            ->paginate(15, false, [
                'query' => Request::instance()->request()
            ])->toArray();
    }

    /**
     * 订单下商品
     */
    public function orderGoods($where,$field)
    {
        // 获取数据列表
        return DB::table('bfb_order_goods')
            ->where($where)
            ->order(['create_time' => 'desc'])
            ->field($field)
            ->select();
    }

    /**
     * 送货地址
     */
    public function orderAddress($where)
    {
        // 获取数据列表
        return DB::table('bfb_order_address')
            ->alias('a')
            ->join('bfb_city b','a.province_id = b.province_id')
            ->join('bfb_city c','a.city_id = c.city_id')
            ->join('bfb_city d','a.region_id = d.district_id')
            ->where($where)
            ->order(['create_time' => 'desc'])
            ->field('a.*,b.name as provincename,c.name as cityname,d.name as regionname')
            ->find();
    }


    /**
     * 订单详情
     */
    public static function orderdetail($where)
    {

        return DB::table('bfb_order')
            ->alias('a')
            ->leftJoin('bfb_merchant b', 'a.merchant_id=b.merchant_id')
            ->where($where)
            ->field(['b.merchant_name','a.order_id','a.pay_time','a.pay_price','a.order_no','a.create_time','a.pay_type','a.pay_status','a.order_types','a.total_price'])
            ->find();

    }

    /**
     * 订单详情
     */
    public static function goodslist($where)
    {

        return DB::table('bfb_order_goods')
            ->where('order_id','=',$where)
            ->select();

    }

    /**
     * 订单金额详情
     */
    public static function orderpul($where)
    {

        return DB::table('bfb_order')
            ->where($where)
            ->find();

    }


    /**
     * 订单地址
     */
    public static function adress($id)
    {

        return DB::table('bfb_order_address')
            ->alias('a')
            ->Join('bfb_region b', 'a.province_id=b.id')
            ->Join('bfb_region c', 'a.city_id=c.id')
            ->Join('bfb_region d', 'a.region_id=d.id')
            ->where('bfb_order_address.order_id','=',$id)
            ->field(['a.*','b.name as province_name','c.name as city_name','d.name as region_name'])
            ->find();

    }

    /**
     * 修改订单价格
     */
    public static function updatice($data,$info)
    {
        if(empty($data['update_price'])){
            return 1002;
        }

        // 实际付款金额
        $payPrice = $data['update_price'];

        if ($payPrice <= 0) {
            //$this->error = '订单实付款价格不能为0.00元';
            return 1001;
        }
        $code = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);

        return DB::table('bfb_order')
            ->where('order_id','=',$data['id'])
            ->update([
                'order_no' => $code, // 修改订单号, 否则微信支付提示重复
                'pay_price' => $payPrice,
                'update_price' => $data['update_price'] - ($info['total_price'] - $info['coupon_price']),
            ]);
    }

    /**
     * 取消订单
     */
    public static function orderdel($id,$u_id,$order_types)
    {
        $where['bfb_order.merchant_id'] =$u_id;
        $where['bfb_order.order_id'] =$id;
        $goods=self::goodslist($id);

        // 启动事务
        Db::startTrans();
        try{
            Db::table('bfb_order')->where('order_id','=',$id)->update(['order_types' => $order_types]);
            if(!empty($goods)&&count($goods)>0){
                foreach ($goods as $vel){
                    Db::table('bfb_item')->where('goods_id','=',$vel['item_id'])->setInc('store_count',$vel['total_num']);
                }
            }
            // 提交事务
            Db::commit();
            return 1000;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return 1003;
        }
    }

    /**
     * pingjialist
     */
    public static function pingjialist($id)
    {

         $list = DB::table('bfb_item_ping')
             ->alias('a')
             ->join('bfb_user b','a.uid = b.user_id')
             ->field(['a.*','b.nickName','b.avatarUrl'])
            ->where('a.itemid','=',$id)
             ->where('a.is_delete',1)
            ->select();

        return $list;

    }

    /**
     * pingjialist
     */
    public static function pcpingjialist($id ='',$state)
    {
        if(!empty($id)){
            $where['a.itemid'] = $id;
        }else{
            $where = [];
        }
        $houtai = Session::get('houtaizhuangtai');
        if(!empty($houtai)&&$houtai ==1){
            $where['c.user_id']=self::$user_id;
        }

        $list = DB::table('bfb_item_ping')
            ->alias('a')
            ->join('bfb_user b','a.uid = b.user_id')
            ->join('bfb_item c','a.itemid = c.goods_id')
            ->where($where)
            ->where('a.is_delete',1)
            ->where('c.state',$state)
            ->field('a.*,FROM_UNIXTIME(a.create_time,"%Y-%m-%d %H:%i") as timead,b.nickName,c.goods_name,c.good_image')
            ->order('a.create_time desc')
            ->paginate(15, false, [
                'query' => Request::instance()->request()
            ]);

        return $list;

    }


    public function setDelete($id)
    {
        return Db::table('bfb_item_ping')
            ->where('item_ping_id',$id)->update(['is_delete'=>'2']);
    }


    /**
     * pingjialist
     */
    public static function pingjialistad($id)
    {
        $list = DB::table('bfb_item_ping')
            ->where('pid','=',$id)
            ->find();
        return $list;
    }

    /**
     * pingjialist
     */
    public static function pingjialistadd($info)
    {
        $add['name'] = $info['txt'];
        $add['pid'] = $info['id'];
        $add['time'] = date('Y-m-d H:i:s',time());
        return DB::table('bfb_item_ping')
            ->insert($add);
    }
    /**
     * 获取订单总数量
     */
    public function getOrderTotal($filter = [])
    {
        return $this->where($filter)->count();
    }
    /**
     * 获取某天的总销售额
     */
    public function rderTotalPrice($id,$day)
    {
        $startTime = strtotime($day);
        return $this->where('pay_time', '>=', $startTime)
            ->where('pay_time', '<', $startTime + 86400)
            ->where('pay_status', '=', 20)
            ->where('merchant_id', '=', $id)
            ->sum('pay_price');
    }
    /**
     * 获取一天订单总数 (可指定某天)
     */
    public function onerderTotal($id,$day = null)
    {
        $filter = [];
        if (!is_null($day)) {
            $startTime = strtotime($day);
            $filter['pay_time'] = ['between',$startTime,$startTime + 86400];
            $filter['merchant_id'] = $id;
        }
        return $this->getOrderTotal($filter);
    }
    /**
     * 获取订单总数量
     */
    public function rderTotal($id)
    {
        $filter['merchant_id'] = $id;
        return $this->where($filter)->count();
    }

    /**
     * 获取总销售额
     */
    public function rderTotalmon($id)
    {
        return $this
            ->where('merchant_id','=',$id)
            ->where('pay_status', '=', 20)
            ->sum('pay_price');
    }



    /**
     * 订单列表
     */
    public function pcgetLists($dataType,$query = [],$state = '1')
    {

        $where=$this->transferDataType($dataType);

        $houtai = Session::get('houtaizhuangtai');
        if(!empty($houtai)&&$houtai ==1){
            $where['merchant_id']=self::$user_id;
        }
        $where['state']=$state;

        // 检索查询
        $this->setWhere($query);

        // 获取数据列表
        return $this->with(['goods.image', 'address', 'user'])
            ->where($where)
            ->order(['create_time' => 'desc'])
            ->paginate(10, false, [
                'query' => Request::instance()->request()
            ]);
    }

    /**
     * pingjialist
     */
    public static function xiangxiList($id)
    {

        $list = DB::table('bfb_item_ping')
            ->where('itemid','in',$id)
            ->where('is_delete',1)
            ->where('pid','=',0)
            ->paginate(15, false, [
                'query' => Request::instance()->request()
            ])->toArray();

        return $list;

    }

    /**
     * pingjialist
     */
    public static function itemlist($id,$state)
    {

        $list = DB::table('bfb_item')
            ->where('user_id','=',$id)
            ->where('state',$state)
            ->field('goods_id')
            ->select();

        return $list;

    }

    /**
     * pingjialist
     */
    public function logList($id,$state)
    {
        $list = DB::table('bfb_merchant_log')
            ->where('user_id','=',$id)
            ->where('state',$state)
            ->where('code','=','1')
            ->order('create_time desc')
            ->select();
        return $list;
    }

    /**
     * pingjialist
     */
    public function logfind($id)
    {
        $list = DB::table('bfb_merchant_log')
            ->where('merchant_log_id','=',$id)
            ->find();
        return $list;
    }
    /**
     * pingjialist
     */
    public function logListad($id,$state)
    {
        $list = DB::table('bfb_merchant_log')
            ->where('user_id','=',$id)
            ->where('state',$state)
            ->where('code','=','2')
            ->order('create_time desc')
            ->select();
        return $list;
    }


    /**
     * pingjialist
     */
    public function logListUp($id,$state,$where)
    {
        $list = DB::table('bfb_merchant_log')
            ->where('user_id','=',$id)
            ->where('state',$state)
            ->where($where)
            ->where('code','=','1')
            ->update(['code'=>'2']);
        return $list;
    }

    /**
     * pingjialist
     */
    public function jinduAdd($where)
    {
        $list = DB::table('bfb_order_jindu')
            ->insert($where);
        return $list;
    }

    /**
     * 订单详情
     */
    public static function jindufind($where)
    {

        return DB::table('bfb_order_jindu')
            ->where($where)
            ->order('create_time asc')
            ->select();

    }

    /**
     * pingjialist
     */
    public function querenFahuo($where,$upda)
    {
        $list = DB::table('bfb_order')
            ->where($where)
            ->update($upda);
        return $list;
    }

}